package com.myebills.ebpsfrontend.cust.maxis;

import com.myebills.ebpsfrontend.cust.controller.*;
import com.myebills.ebpsfrontend.cust.utils.*;
import com.checkfree.isolutions.customer.persist.Account;
import com.checkfree.isolutions.customer.persist.User;
import com.checkfree.isolutions.customer.persist.Merchant;
import com.checkfree.isolutions.customer.persist.MerchantHomeImpl;
import com.checkfree.isolutions.admin.ObjectId;
import com.checkfree.isolutions.statement.persist.Statement;
import com.checkfree.isolutions.statement.StatementSection;
import com.checkfree.isolutions.property.Properties;
import com.checkfree.isolutions.property.PropertiesConfig;
import java.text.*;
import java.util.*;
import java.text.SimpleDateFormat;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.InputStream;
import javax.servlet.ServletOutputStream;

public class DownloadBillServlet_v1r00 extends EbppxTransactionServlet {

    /**
     * Load statement and account objects into request.
     * Expecting "statementId" and "accountId" in request.
     */
    public void doTransaction(HttpServletRequest req, HttpServletResponse res)
    throws ServletException {
        try {
            final HttpSession session = req.getSession(false);
            if (null == session) {
                throw new ServletException("Session must be already established");
            }
			System.out.println("stmtIdxstmtIdxstmtIdxstmtIdxstmtIdxstmtIdxstmtIdxstmtIdx1");
    		final String randomKey = (String) session.getAttribute(EbppxConstants.RANDOM_KEY);

            final EbppxUrlManager urlManager = getUrlManager(req);

            final String sOidStatement = urlManager.getSecureParameter(EbppxConstants.STATEMENT_ID);
            if (sOidStatement.length() == 0) {
                throw new ServletException("Missing statement identifier");
            }

            final String sOidAccount   = urlManager.getSecureParameter(EbppxConstants.ACCOUNT_ID);
            if (sOidAccount.length() == 0) {
                throw new ServletException("Missing account identifier");
            }


            final EbppxEcsUser ecsUser = (EbppxEcsUser) session.getAttribute(EbppxConstants.ECS_USER);
            Merchant cfiMerchant = MerchantHomeImpl.singleton().findByName(ecsUser.getMerchantName());
            User cfiUser = getUserHome().findByLogonIdAndMerchant(ecsUser.getUserId(),cfiMerchant);

            final Account acct = getAccountHome().findById(new ObjectId(EncryptionHelper.decrypt(sOidAccount,randomKey)));
            final Statement stmt = getStatementHome().findById(new ObjectId(EncryptionHelper.decrypt(sOidStatement,randomKey)));

            final char cfiUserRole = cfiUser.getRole();
            //final Statement cfiStatement = (Statement)req.getAttribute(EbppxConstants.CFI_STATEMENT);

            final String fromPage = (String) session.getAttribute("fromPage");
            String stmtIndex = urlManager.getSecureParameter("stmtIndex");
            if (stmtIndex.length() == 0) {
                stmtIndex = "0";
            }
            //final int stmtIdx =  Integer.parseInt(EncryptionHelper.decrypt(stmtIndex,randomKey));

            //Start ==> Check for the firstime execution of this servlet for this user session
            String displayTNC = urlManager.getSecureParameter("displayTNC");
            if (displayTNC.equals("")) {
                final String cfiUserPropertyTNCResp = cfiUser.getProperty("TNCResp");
				System.out.println("cfiUserPropertyTNCResp ===== " + cfiUserPropertyTNCResp);
                if (cfiUserPropertyTNCResp.equals("YES")) {
                    displayTNC = "NO";
                } else{
                    displayTNC = "YES";
                }
            }//if TNCResp equal to empty
            //End==> Check for the firstime execution of this servlet for this user session

            //Start ==> Check if user click on the Agree button on the TNC, if yes then update user property TNCResp
            String updateTNC = "";
            updateTNC = urlManager.getSecureParameter("updateTNC");
			System.out.println("updateTNC ===== " + updateTNC);
            if (updateTNC.equals("YES")) {//original = YES
                cfiUser.setProperty("TNCResp", "YES");//original ="YES"
                displayTNC = "NO";
            }//need to update TNCResp
            //End ==> Check if user click on the Agree button on the TNC, if yes then update user property TNCResp

            String PDFExceedLimit = "";
            String PDFExceedLimitMsg = "";
            InputStream inStream = stmt.getExternalFormatData(); // actual downloading of file in pdf

            //Get PDF Max size
            int FILESIZELIMIT = 0;
            Properties appCfg = PropertiesConfig.getApplicationSettings();
            if (appCfg.hasProperty("PdfMaxSize") == false)
                FILESIZELIMIT = 2097152;
            else
                FILESIZELIMIT = Integer.parseInt(appCfg.getProperty("PdfMaxSize"));

            System.out.println("File size : " + FILESIZELIMIT);

            if (displayTNC.equals("NO")) {
                int PDFSize = inStream.available();
                if (PDFSize > FILESIZELIMIT) {
                    PDFExceedLimitMsg = "YES";
                } else {
                    PDFExceedLimitMsg = "NO";
                    PDFExceedLimit = "NO";
                }

            }// if displayTNC = NO
			System.out.println("stmtIdxstmtIdxstmtIdxstmtIdxstmtIdxstmtIdxstmtIdxstmtIdx1");
            //getting ready to download either PDF of CSV file
            String filename = "";
            if (PDFExceedLimit.equals("NO") ) {

                final Date dtVal = stmt.getDate();

                final DateFormat dfdisp = new SimpleDateFormat("ddMMMyyyy");
                String stdate = EbppxUtil.htmlEncode(dfdisp.format(dtVal));

                filename = new String(acct.getExternalKey()+"-"+stdate);
                filename += ".pdf";

                // log activity start
                String dateString = DateUtil.formatDate(new Date());
                String stmtDateString = DateUtil.formatDate(dtVal);
                EbppxCusDBUtil.logUserActivity(EbppxConstants.DOWNLOAD_PDF, acct.getExternalKey(),ecsUser.getUserId(),EbppxConstants.CUSTOMER, EbppxConstants.STATUS_DOWNLOADED, dateString,stmtDateString,"","","","");
                // log activity end

            }//if PDFExceedLimt = NO or (PDFExceedLimit = Yes and msgprompt to download CSV = Yes)
			
			String justDisplay = "0";
			int intjustDisplay = 0;
			justDisplay = urlManager.getSecureParameter("justDisplay");
			if(justDisplay != null && justDisplay != ""){
				intjustDisplay = Integer.parseInt(justDisplay) + 1;
			}
			
            stmt.view();
			req.setAttribute("justDisplay", Integer.toString(intjustDisplay));
            req.setAttribute(EbppxConstants.CFI_ACCOUNT, acct);
            req.setAttribute(EbppxConstants.CFI_STATEMENT, stmt);
            req.setAttribute("displayTNC", displayTNC);
            req.setAttribute("PDFExceedLimit", PDFExceedLimit);
            req.setAttribute("PDFExceedLimitMsg", PDFExceedLimitMsg);
            req.setAttribute("inStream", inStream);
            req.setAttribute("filename", filename);
            req.setAttribute("fromPage", fromPage);
            req.setAttribute("stmtIndex", EncryptionHelper.decrypt(stmtIndex,randomKey));
			System.out.println("stmtIdxstmtIdxstmtIdxstmtIdxstmtIdxstmtIdxstmtIdxstmtIdx3");
            forwardToMappedUrl(req, res, EbppxConstants.URL_JSP_PARAM);
        } catch (ServletException e) {
            // Just re-throw these
            throw e;
        } catch (Throwable t) {
            throw new ServletException(t.toString(), t);
        }
    }
}